import React,{useEffect, useRef, useState} from "react";
import './index.less'
import { useNavigate, useLocation, useParams } from 'react-router-dom';
import {io} from 'socket.io-client';

import utils from '../../util/utils'
import http from '../../util/http'

function OnlineChat(props){
  // 当前客户端的socket对象
  let socket=useRef(null);
  // 当前客户端的socketId
  let [socketId,setSocketId] = useState("");
  // 聊天记录消息列表
  const [messageList,setMessageList] = useState([]);
  // 发送者
  const from = {
    UserId: props.from.UserId,
    Nickname: props.from.Nickname,
    AvatarUrl:props.from.AvatarUrl
  }
  // 接收者
  const to = {
    UserId: props.to.UserId,
    Nickname: props.to.Nickname,
    AvatarUrl:props.to.AvatarUrl
  }
  

  const closeConnect = ()=>{
    const params = {
      from,
      to,
    }
    http.post("/onlineChat/close",params).then(res=>{})
  }
  
  useEffect(()=>{
    // const params = {
    //   from,
    //   to,
    // }
    // http.post("/onlineChat/connection",params).then(res=>{
      socket.current = io("ws://127.0.0.1:4444");
      socket.current.on("connect", () => {
        console.log(`连接成功`,socket.current.id);
      });
      socket.current.on("disconnect", () => {
          console.log("断开连接"); 
          closeConnect()
      });
      //实时监听 谁给我发消息

      socket.current.on("receiveMessage",(data)=>{
        const { Info, ChatContent, CreateTime } = data;
      
        setMessageList((preData)=>{
          let newData = [...preData];
          newData.push({
            UserId:Info.from.UserId,
            Nickname:Info.from.Nickname,
            AvatarUrl:Info.from.AvatarUrl,
            ChatContent,
            CreateTime,
            isMeSent:false
          }) 
          return newData;
        })
      // })

    })

    return ()=>{
      if(socket.current){
        socket.current.disconnect();
      }
    }
  },[])
 
  const changeOnlineBoxIsShow = ()=>{
    props.setOnlineBoxIsShow((preValue)=>{
      return !preValue;
    })
  }

  const [chatContent,setChatContent] = useState("");
  const changeChatContent= (e)=>{
    setChatContent((preValue)=>{
      return e.target.value
    })
  }
  
  const sendChatContent = ()=>{
    if(!chatContent){
      return
    }
    let CreateTime = new Date().getTime();
    const data = {
      Info:{
        //发送方
        from,
        //接收方
        to,
      },
      ChatContent:chatContent,
      CreateTime
    };
    // 发送消息
    socket.current.emit(`sendMessage`,data,()=>{
      //服务端接收完消息后,将消息发给“接收方”
      //自己发的消息加入“聊天记录” 显示在右边
      setMessageList((preData)=>{
        let newData = [...preData];
        newData.push({
          UserId:from.UserId,
          Nickname:from.Nickname,
          AvatarUrl:from.AvatarUrl,
          ChatContent:chatContent,
          CreateTime,
          isMeSent:true
        }) 
        return newData;
      })

      setChatContent(()=>"")
    })
  }
  return (
    <React.Fragment>
      <div className="online-box">
          <div className="online-head">
            <div className="zz-info">
              <div>
                站长：范范范
              </div>
              <div>
                微信：madmanfzy
              </div>
            </div>
            <i className="iconfont icon-cuocha_kuai" onClick={changeOnlineBoxIsShow.bind(this)}>
            </i>
          </div>

          <div className="chat-list">
            {
              messageList && messageList.map((item,index)=>(
                <React.Fragment key={index}>
                  <div className={item.isMeSent ? "chat-item chat-right" : "chat-item chat-left"}>
                    <img className="chat-user-img" src={item.AvatarUrl} alt="" />
                    <div className="chat-cont-wrap">
                      <div className="chat-time">
                        {utils.timeStampToDate(item.CreateTime) }
                      </div>
                      <div className="chat-cont">
                        {item.ChatContent}
                      </div>
                    </div>
                  </div>
                </React.Fragment>
              ))
            }
            
          </div>
          <div className="chat-input-wrap">
            <textarea type="text" value={chatContent} onChange={(e)=>changeChatContent(e)} 
            placeholder="请输入内容"
            
            />

            <span className="send-btn" onClick={sendChatContent}>
              发送
              <i className="iconfont icon-duigou_kuai"></i>
            </span>
          </div>
      </div>
    </React.Fragment>
  )
}

export default OnlineChat